//
//  SearchViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/5.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchRecordViewController.h"

#import "SearchCollectionViewCell.h"

#import "EqualCellSpaceFlowLayout.h"

@interface SearchViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) UITextField *searchField;
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *searchRecords;

@end

@implementation SearchViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    [self setNavBar];
    [self getSearchRecords];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
//    flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 15, 13);
//    flowLayout.minimumInteritemSpacing = 13;
//    flowLayout.minimumLineSpacing = 15;
    EqualCellSpaceFlowLayout *flowLayout = [[EqualCellSpaceFlowLayout alloc] initWithType:AlignWithLeft betweenOfCell:ScreenX375(10)];
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.alwaysBounceVertical = YES;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.scrollEnabled = NO;
    [_collectionView registerClass:[SearchCollectionViewCell class] forCellWithReuseIdentifier:@"searchCell"];
    
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headCell1"];
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headCell2"];
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footCell"];
    
    [self.view addSubview:_collectionView];
}

- (void)setNavBar {
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 14, 44)];
    [backBtn setImage:[UIImage imageNamed:@"返回白色"] forState:UIControlStateNormal];
    backBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 10);
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 52, 30)];
    UIImageView *leftImg = [[UIImageView alloc] initWithFrame:CGRectMake(20, 4, 22, 22)];
    leftImg.image = [UIImage imageNamed:@"搜索"];
    [leftView addSubview:leftImg];
    
    _searchField = [[UITextField alloc] initWithFrame:CGRectMake(0, 7, SCREEN_WIDTH - ScreenX375(54), 30)];
    _searchField.placeholder = @"找专业的人才做专业的事情";
    _searchField.layer.cornerRadius = ScreenX375(15);
    _searchField.clipsToBounds = YES;
    _searchField.backgroundColor = [UIColor whiteColor];
    _searchField.leftViewMode = UITextFieldViewModeAlways;
    _searchField.leftView = leftView;
    _searchField.font = Kfont(13);
    _searchField.returnKeyType = UIReturnKeySearch;
    _searchField.delegate = self;
    self.navigationItem.titleView = _searchField;
}

- (void)backClick {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)getSearchRecords {
    _searchRecords = [NSMutableArray array];
    //获取搜索记录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *document = paths[0];
    NSString *plistPath = [document stringByAppendingPathComponent:@"searchRecords.plist"];
    //判断是否以创建文件
    if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
    {
        //如果没有plist文件就自动创建
        NSMutableArray *array = [NSMutableArray array];
        //写入文件
        [array writeToFile:plistPath atomically:YES];
    }
    _searchRecords = [NSMutableArray arrayWithContentsOfFile:plistPath];
    [_collectionView reloadSections:[NSIndexSet indexSetWithIndex:1]];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 1) {
        return _searchRecords.count;
    }
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"searchCell" forIndexPath:indexPath];
    cell.layer.cornerRadius = ScreenX375(15);
    cell.layer.borderWidth = 1;
    if (indexPath.row == 0) {
        cell.layer.borderColor = ThemeColor.CGColor;
        cell.textLabel.textColor = ThemeColor;
    }else {
        cell.layer.borderColor = LineColor.CGColor;
        cell.textLabel.textColor = REXADECIMALCOLOR(@"#999999");
        
    }
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"彩印设计";
        }else if (indexPath.row == 1){
            cell.textLabel.text = @"水印设计";
        }else if (indexPath.row == 2){
            cell.textLabel.text = @"数码设计";
        }else{
            cell.textLabel.text = @"结构设计";
        }
    }else {
        cell.textLabel.text = _searchRecords[indexPath.item];
    }
    cell.clipsToBounds = YES;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SearchCollectionViewCell *cell = (SearchCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    SearchRecordViewController *vc = [[SearchRecordViewController alloc] init];
    vc.searchKey = cell.textLabel.text;
    [self.navigationController pushViewController:vc animated:YES];
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableView = nil;
    if(kind == UICollectionElementKindSectionHeader)
    {
        if (indexPath.section == 0) {
            UICollectionReusableView *headerView = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headCell1" forIndexPath:indexPath];
            headerView.backgroundColor = [UIColor whiteColor];
            
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(15), ScreenX375(3), ScreenX375(23))];
            line.backgroundColor = ThemeColor;
            [headerView addSubview:line];
            
            UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(15), ScreenX375(200), ScreenX375(24))];
            noteLabel.text = @"热门搜索";
            noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
            noteLabel.font = Kfont(18);
            [headerView addSubview:noteLabel];
            
            return headerView;
        }else {
            UICollectionReusableView *headerView = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headCell2" forIndexPath:indexPath];
            headerView.backgroundColor = [UIColor whiteColor];
            
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(15), ScreenX375(3), ScreenX375(23))];
            line.backgroundColor = ThemeColor;
            [headerView addSubview:line];
            
            UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(15), ScreenX375(200), ScreenX375(24))];
            noteLabel.text = @"最近搜索";
            noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
            noteLabel.font = Kfont(18);
            [headerView addSubview:noteLabel];
            
            return headerView;
        }
    }
    else if(kind == UICollectionElementKindSectionFooter)
    {
        if (indexPath.section == 0) {
            UICollectionReusableView *footerView = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footCell" forIndexPath:indexPath];
            footerView.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
            
            return footerView;
        }else {
            return nil;
        }
    }
    reusableView.backgroundColor = [UIColor whiteColor];
    
    return reusableView;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(SCREEN_WIDTH, ScreenX375(53));
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(SCREEN_WIDTH, ScreenX375(10));
    }
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *key = @"包装设计";
    if (indexPath.section == 1) {
        key = _searchRecords[indexPath.item];
    }
    CGRect rect = [key boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 26, 100) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:Kfont(14)} context:nil];
    return CGSizeMake(rect.size.width + ScreenX375(36), ScreenX375(30));
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [_searchField resignFirstResponder];
    NSLog(@"搜索");
    
    //搜索方法
    [self searchClick];
    return NO;
}

- (void)searchClick{
    [_searchField resignFirstResponder];
    
    SearchRecordViewController *vc = [[SearchRecordViewController alloc] init];
    vc.searchKey = _searchField.text;
    [self.navigationController pushViewController:vc animated:YES];
    
    //保存搜索记录
    if (![[_searchField.text stringByReplacingOccurrencesOfString:@" " withString:@""] isEqualToString:@""]){
        NSString *str = [NSString stringWithFormat:@"%@",_searchField.text];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *document = paths[0];
        NSString *plistPath = [document stringByAppendingPathComponent:@"searchRecords.plist"];
        if (![_searchRecords containsObject:str]) {
            [_searchRecords addObject:str];
            
            [_searchRecords writeToFile:plistPath atomically:YES];
            [_collectionView reloadSections:[NSIndexSet indexSetWithIndex:1]];
        }
    }
    
    _searchField.text = @"";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
